package com.objcat.servicesecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.objcat.servicesecurity.entity.po.PowerPo;
import com.objcat.servicesecurity.entity.po.RolePo;
import com.objcat.servicesecurity.entity.po.RolePowerPo;
import com.objcat.servicesecurity.entity.vo.PowerVo;
import com.objcat.servicesecurity.mapper.PowerMapper;
import com.objcat.servicesecurity.service.PowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.objcat.servicesecurity.service.RolePowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author misheep
 * @since 2020-07-29
 */
@Service
public class PowerServiceImpl extends ServiceImpl<PowerMapper, PowerPo> implements PowerService {

    @Autowired
    private PowerMapper powerMapper;
    @Autowired
    private RolePowerService rolePowerService;

    /**
     * 通过角色获取资源权限
     * @param rolePo
     * @return
     */
    @Override
    public List<PowerVo> getPowers(RolePo rolePo) {
        List<RolePowerPo> rolePowerPoList = rolePowerService.getRolePower(rolePo);
        QueryWrapper<PowerPo> queryWrapper = new QueryWrapper<>();
        rolePowerPoList.forEach(rolePowerPo -> {
            queryWrapper.eq("power_id",rolePowerPo.getPowerId());
        });
        List<PowerPo> powerPoList = powerMapper.selectList(queryWrapper);
        return toPowerVoList(powerPoList);
    }

    /**
     * 获取全部权限资源
     * @return
     */
    @Override
    public List<PowerPo> getAllPowers() {
        QueryWrapper<PowerPo> queryWrapper = new QueryWrapper<>();
        return powerMapper.selectList(queryWrapper);
    }

    /**
     * 转换Vo
     * @param powerPo
     * @return
     */
    @Override
    public PowerVo toPowerVo(PowerPo powerPo) {
        if(powerPo==null) {
            return null;
        }
        PowerVo powerVo = new PowerVo();
        powerVo.setPowerId(powerPo.getPowerId());
        powerVo.setPowerName(powerPo.getPowerName());
        powerVo.setUrl(powerPo.getUrl());
        return powerVo;
    }

    /**
     * 转换VoList
     * @param powerPoList
     * @return
     */
    @Override
    public List<PowerVo> toPowerVoList(List<PowerPo> powerPoList) {
        if(powerPoList.size()<=0) {
            return null;
        }
        List<PowerVo> powerVoList = new ArrayList<>();
        powerPoList.forEach(powerPo -> {
            powerVoList.add(toPowerVo(powerPo));
        });
        return powerVoList;
    }

}
